package com.demo.sender.email;

import com.demo.common.ResultData;
import com.demo.enums.EmailChannelEnum;
import com.demo.request.EmailSenderReq;
import com.demo.sender.email.handler.EmailSenderHandler;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author wangfengchen
 */
@Service("emailSenderService")
public class EmailSenderRouter implements EmailSenderService {


  @Autowired
  private EmailSenderHandler emailSenderHandler;

  /**
   * 多渠道发送邮件切换
   */
  @Value("${email.sender:aws}")
  private String emailSender;


  private EmailSenderService getEmailSenderHandler(Integer channel) {
    if (channel == null) {
      EmailChannelEnum emailSenderEnum = EmailChannelEnum.match(emailSender.toUpperCase());
      if (ObjectUtils.isEmpty(emailSenderEnum)) {
        // 默认aws
        channel = EmailChannelEnum.AWS.getCode();
      } else {
        channel = emailSenderEnum.getCode();
      }
    }
    return emailSenderHandler.getEmailSenderHandler(channel);
  }

  @Override
  public ResultData<Object> send(EmailSenderReq request) {
    return getEmailSenderHandler(request.getChannel()).send(request);
  }

  @Override
  public ResultData<Object> sendAsync(EmailSenderReq request) {
    return getEmailSenderHandler(request.getChannel()).sendAsync(request);
  }

  @Override
  public void sendWithAttachmentAsync(EmailSenderReq request) {
    getEmailSenderHandler(request.getChannel()).sendWithAttachmentAsync(request);
  }

}
